package com.example.project.frag_record;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.project.MyApplication;
import com.example.project.R;
import com.example.project.activity.kaishi.LoginActivity;
import com.example.project.activity.jizhang.RecordActivity;
import com.example.project.adapter.TypeBaseAdapter;
import com.example.project.bean.AccountBean;
import com.example.project.bean.TypeBean;
import com.example.project.dialog.BeiZhuDialog;
import com.example.project.dialog.SelectTimeDialog;
import com.example.project.utils.KeyBoardUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public abstract class BaseRecordFragment extends Fragment implements View.OnClickListener {
     KeyboardView keyboardView; //小键盘
     EditText moneyET; //显示输入的金额
     ImageView tyoelv; //选中时的图标
     TextView typeTv,beizhuTv,timeTv; //类型，备注，事件
     GridView typeGv; //网格布局
     List<TypeBean> typeList;
     TypeBaseAdapter adapter;
     AccountBean accountBean; //将插入到记账本的数据保存到对象
     int mainId; //记录登录时的id
     ProgressDialog pd; //消息提示框

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        accountBean=new AccountBean(  );
    }

    //创建该fragment对应的视图
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate( R.layout.fragment_outcome ,container,false);
        //初始化
        initView(view);
        //获取当前时间，显示出来
        setInitTime();
        //给GeridVIew填充数据的方法
        loadDateToGv();
        //设置GridView每一项的点击事件
        setGVListener();
        return view;
    }

    //初始化
    private void initView(View view) {
        mainId= MyApplication.getMainId(); //获取登录时的id

        keyboardView=view.findViewById( R.id.frag_record_keyboard );
        moneyET=view.findViewById( R.id.frag_record_et_money );
        tyoelv=view.findViewById( R.id.frag_record_iv );
        typeGv=view.findViewById( R.id.frag_record_gv );
        typeTv=view.findViewById( R.id.frag_record_tv_type );
        beizhuTv=view.findViewById( R.id.frag_record_tv_beizhu );
        timeTv=view.findViewById( R.id.frag_record_tv_time );
        beizhuTv.setOnClickListener( this );
        timeTv.setOnClickListener( this );
        pd = new ProgressDialog(getContext());

        //让自定义软键盘显示出来
        KeyBoardUtils boardUtils=new KeyBoardUtils( keyboardView , moneyET );

        //设置接口，监听确定按钮是否被点击了
        boardUtils.setOnEnsureListener( new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure() {
                if(mainId==0){
                    AlertDialog alertDialog2 = new AlertDialog.Builder(getContext())
                            .setTitle("警告")
                            .setMessage("你还未登录")
                            .setIcon(R.drawable.jg)
                            .setPositiveButton("取消", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    return;
                                }
                            })

                            .setNegativeButton("登录", new DialogInterface.OnClickListener() {//添加取消
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Intent intent=new Intent( getContext(), LoginActivity.class );
                                    startActivity( intent );
                                }
                            })
                            .create();
                    alertDialog2.show();
                }else {
                    //获取输入的钱数
                    String moneyStr=moneyET.getText().toString();
                    if(TextUtils.isEmpty( moneyStr ) || moneyStr.equals( "0" )){ //为空或者为0，则返回上一个页面
                        getActivity().finish();
                        return;
                    }

                    float money=Float.parseFloat( moneyStr ); //强转为float类型
                    DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String p=decimalFormat.format(money);//format 返回的是字符串
                    float moneys=Float.parseFloat(p);
                    accountBean.setMoney( moneys ); //将金额保存起来
                    //获取记录的信息，保存至数据库中
                    saveAccountToDB();
                    //返回上一级页面
                    Intent intent=new Intent( getActivity(), RecordActivity.class );
                    startActivity( intent );
                }
            }
        } );
    }

    //获取当前时间，显示出来
    private void setInitTime() {
        Date date=new Date(  ); //实例化时间
        SimpleDateFormat sdf=new SimpleDateFormat( "yyyy年MM月dd日 HH:mm" ); //设置日期格式
        String time=sdf.format( date ); //将时间加载为日期格式
        timeTv.setText( time ); //设置时间
        accountBean.setTime( time ); //将时间保存起来

        Calendar calendar=Calendar.getInstance(); //获取日历的实例
        int year=calendar.get( calendar.YEAR ); //获取年
        int month=calendar.get( calendar.MARCH )+1; //获取月（0-11），所以要+1
        int day=calendar.get( calendar.DAY_OF_MONTH ); //获取日
        accountBean.setYear( year ); //将年保存起来
        accountBean.setMonth( month ); //将月保存起来
        accountBean.setDay( day ); //将日保存起来
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.frag_record_tv_time:
                SelectTimeDialog dialog=new SelectTimeDialog( getContext() ); //实例化时间对话框
                dialog.show(); //显示出来
                //设置确定按钮被点击了的监听器
                dialog.setOnEnsureListener( new SelectTimeDialog.OnEnsureListener() {
                    @Override
                    public void onEnsure(String time, int year, int month, int day) {
                        timeTv.setText( time ); //重新给时间赋值
                        accountBean.setTime( time ); //将时间保存起来
                        accountBean.setYear( year ); //将年保存起来
                        accountBean.setMonth( month ); //将月保存起来
                        accountBean.setDay( day ); //将日保存起来
                    }
                } );
                break;
            case R.id.frag_record_tv_beizhu:
                showBZDialog(); //弹出备注对话框
                break;
        }
    }

    //弹出备注对话框
    protected void showBZDialog(){
        final BeiZhuDialog dialog=new BeiZhuDialog( getContext() );
        dialog.show(); //显示弹窗
        dialog.setDialogSize(); //动态设置弹窗大小
        dialog.setOnEnsureListener( new BeiZhuDialog.OnEnsureListener() {
            @Override
            public void onEnsure() {
                String msg=dialog.getEditText(); //将备注的信息获取出来
                if(!TextUtils.isEmpty( msg )){ //如果为空，就还剩设置为空的
                    beizhuTv.setText( msg );
                    accountBean.setBeizhu( msg );
                }
                dialog.cancel(); //废除对话框，才能进行activity销毁
            }
        } );

    }

    //给GeridVIew填充数据的方法，子类重写将数据传入
    public void loadDateToGv() {
        typeList=new ArrayList<>(  );
        adapter=new TypeBaseAdapter( getContext(),typeList );
        typeGv.setAdapter( adapter );
    }

    //设置GridView每一项的点击事件
    private void setGVListener() {
        typeGv.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.selectPos=position;//判断选中的是第几个照片
                adapter.notifyDataSetChanged(); //刷新提示
                TypeBean typeBean=typeList.get( position ); //获取改选中的信息
                String typeName=typeBean.getTypename(); //获取类型
                typeTv.setText( typeName ); //设置修改类型
                int simageId=typeBean.getSimageId(); //获取变化的图片
                accountBean.setTypename( typeName ); //储存变化的类型
                accountBean.setsImageId( simageId ); //储存变化的图片
                tyoelv.setImageResource( simageId ); //设置选中的图片
            }
        } );
    }

    //抽象方法，让子类一定要重写抽象的方法()
    public abstract void saveAccountToDB();
}
